package ui;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;

import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.border.EmptyBorder;

import org.joda.time.DateTime;
import org.joda.time.LocalDate;

import entity.general.MinTime;
import entity.main.Task;
import entity.main.Task.TaskType;
import java.awt.Toolkit;

public class CreateEditTaskDialog extends JDialog {

	public static class TaskData
	{
		public String name;
		public String description;
		public MinTime allotedTime;
		public boolean hasDeadline = false;
		public LocalDate deadline = null;
		public TaskType taskType;
		public String categoryName;
		
		public TaskData(String n, String d, MinTime at, TaskType tt, String cat)
		{
			name = n;
			description = d;
			allotedTime = at;
			taskType = tt;
			categoryName = cat;
		}
		
		public TaskData(String n, String d, MinTime at, TaskType tt, String cat, LocalDate dead)
		{
			name = n;
			description = d;
			allotedTime = at;
			taskType = tt;
			categoryName = cat;
			hasDeadline = true;
			deadline = dead;
		}		
	}

	static public enum Status {OK, CANCEL};

	private final JPanel contentPanel = new JPanel();
	private JTextField nameField;
	private JTextField minutesTimeField;
	private JTextField hoursTimeField;
	private JTextField dayTextField;
	private JTextField monthTextField;
	private JTextField yearTextField;
	private JComboBox <TaskType> typeComboBox;
	private JCheckBox deadlineCheckbox;
	private JTextPane descriptionTextPane;
	private JComboBox <String> categoryComboBox;
	
	Status status = Status.CANCEL;
	private Task task;
	
	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		try {
			List <String> categories = new ArrayList<>();
			categories.add("Test1");
			categories.add("Test2");
			categories.add("Test3");
			categories.add("Test4");			
			CreateEditTaskDialog dialog = new CreateEditTaskDialog(categories);
			dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
			dialog.setVisible(true);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Create the dialog.
	 * @wbp.parser.constructor
	 */
	public CreateEditTaskDialog(List <String> categories) {
		setIconImage(Toolkit.getDefaultToolkit().getImage(CreateEditTaskDialog.class.getResource("/images/ActivlyIcon.png")));
		this.setTitle("Create New Task");
		init(categories);
	}

	public CreateEditTaskDialog(Task task, List <String> categories) {
		this.setTitle("Edit Task");
		this.task = task;
		init(categories);
		loadDataFromTask();
	}

		
	private void loadDataFromTask() {
		nameField.setText(task.getName());
		minutesTimeField.setText(task.getTimePlanned().getMinutes() + "");
		hoursTimeField.setText(task.getTimePlanned().getHours() + "");

		if(task.getDeadline() != null)
		{
			deadlineCheckbox.setSelected(true);
			dayTextField.setText(task.getDeadline().getDayOfMonth() + "");
			monthTextField.setText(task.getDeadline().getMonthOfYear() + "");
			yearTextField.setText(task.getDeadline().getYear() + "");
		}

		typeComboBox.setSelectedItem(task.getType());
		
		descriptionTextPane.setText(task.getDescription());		
	}

	private void init(List <String> categories)
	{
		setModalityType(ModalityType.DOCUMENT_MODAL);
		setBounds(100, 100, 450, 300);
		getContentPane().setLayout(new BorderLayout());
		contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
		getContentPane().add(contentPanel, BorderLayout.CENTER);
		GridBagLayout gbl_contentPanel = new GridBagLayout();
		gbl_contentPanel.columnWidths = new int[]{0, 0, 0};
		gbl_contentPanel.rowHeights = new int[]{0, 0, 0, 0, 0, 0, 0};
		gbl_contentPanel.columnWeights = new double[]{0.0, 1.0, Double.MIN_VALUE};
		gbl_contentPanel.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0, 1.0, Double.MIN_VALUE};
		contentPanel.setLayout(gbl_contentPanel);
		{
			JLabel lblName = new JLabel("Name");
			GridBagConstraints gbc_lblName = new GridBagConstraints();
			gbc_lblName.insets = new Insets(0, 0, 5, 5);
			gbc_lblName.anchor = GridBagConstraints.EAST;
			gbc_lblName.gridx = 0;
			gbc_lblName.gridy = 0;
			contentPanel.add(lblName, gbc_lblName);
		}
		{
			nameField = new JTextField();
			GridBagConstraints gbc_nameField = new GridBagConstraints();
			gbc_nameField.insets = new Insets(0, 0, 5, 0);
			gbc_nameField.fill = GridBagConstraints.HORIZONTAL;
			gbc_nameField.gridx = 1;
			gbc_nameField.gridy = 0;
			contentPanel.add(nameField, gbc_nameField);
			nameField.setColumns(10);
		}
		{
			JLabel lblCategory = new JLabel("Category");
			GridBagConstraints gbc_lblCategory = new GridBagConstraints();
			gbc_lblCategory.anchor = GridBagConstraints.EAST;
			gbc_lblCategory.insets = new Insets(0, 0, 5, 5);
			gbc_lblCategory.gridx = 0;
			gbc_lblCategory.gridy = 1;
			contentPanel.add(lblCategory, gbc_lblCategory);
		}
		{
			DefaultComboBoxModel <String> comboBoxModel = new DefaultComboBoxModel <String> (); 
			for(String category : categories)
				comboBoxModel.addElement(category);
			categoryComboBox = new JComboBox <String> (comboBoxModel);
			
			GridBagConstraints gbc_categoryComboBox = new GridBagConstraints();
			gbc_categoryComboBox.insets = new Insets(0, 0, 5, 0);
			gbc_categoryComboBox.fill = GridBagConstraints.HORIZONTAL;
			gbc_categoryComboBox.gridx = 1;
			gbc_categoryComboBox.gridy = 1;
			contentPanel.add(categoryComboBox, gbc_categoryComboBox);
		}
		{
			JLabel lblType = new JLabel("Type");
			GridBagConstraints gbc_lblType = new GridBagConstraints();
			gbc_lblType.anchor = GridBagConstraints.EAST;
			gbc_lblType.insets = new Insets(0, 0, 5, 5);
			gbc_lblType.gridx = 0;
			gbc_lblType.gridy = 2;
			contentPanel.add(lblType, gbc_lblType);
		}
		{
			typeComboBox = new JComboBox();
			typeComboBox.setModel(new DefaultComboBoxModel(TaskType.values()));
			GridBagConstraints gbc_typeComboBox = new GridBagConstraints();
			gbc_typeComboBox.insets = new Insets(0, 0, 5, 0);
			gbc_typeComboBox.fill = GridBagConstraints.HORIZONTAL;
			gbc_typeComboBox.gridx = 1;
			gbc_typeComboBox.gridy = 2;
			contentPanel.add(typeComboBox, gbc_typeComboBox);
		}
		{
			JLabel lblTime = new JLabel("Time");
			GridBagConstraints gbc_lblTime = new GridBagConstraints();
			gbc_lblTime.insets = new Insets(0, 0, 5, 5);
			gbc_lblTime.gridx = 0;
			gbc_lblTime.gridy = 3;
			contentPanel.add(lblTime, gbc_lblTime);
		}
		{
			JPanel panel = new JPanel();
			GridBagConstraints gbc_panel = new GridBagConstraints();
			gbc_panel.insets = new Insets(0, 0, 5, 0);
			gbc_panel.anchor = GridBagConstraints.WEST;
			gbc_panel.gridx = 1;
			gbc_panel.gridy = 3;
			contentPanel.add(panel, gbc_panel);
			{
				hoursTimeField = new JTextField();
				hoursTimeField.setText("00");
				panel.add(hoursTimeField);
				hoursTimeField.setColumns(2);
			}
			{
				JLabel lblH = new JLabel("h");
				panel.add(lblH);
			}
			{
				JLabel label = new JLabel(":");
				panel.add(label);
			}
			{
				minutesTimeField = new JTextField();
				minutesTimeField.setText("00");
				panel.add(minutesTimeField);
				minutesTimeField.setColumns(2);
			}
			{
				JLabel lblM = new JLabel("m");
				panel.add(lblM);
			}
		}
		{
			JLabel lblDeadline = new JLabel("Deadline");
			GridBagConstraints gbc_lblDeadline = new GridBagConstraints();
			gbc_lblDeadline.insets = new Insets(0, 0, 5, 5);
			gbc_lblDeadline.gridx = 0;
			gbc_lblDeadline.gridy = 4;
			contentPanel.add(lblDeadline, gbc_lblDeadline);
		}
		{
			JPanel panel = new JPanel();
			GridBagConstraints gbc_panel = new GridBagConstraints();
			gbc_panel.insets = new Insets(0, 0, 5, 0);
			gbc_panel.anchor = GridBagConstraints.WEST;
			gbc_panel.fill = GridBagConstraints.VERTICAL;
			gbc_panel.gridx = 1;
			gbc_panel.gridy = 4;
			
			LocalDate today = DateTime.now().toLocalDate();
			
			contentPanel.add(panel, gbc_panel);
			{
				deadlineCheckbox = new JCheckBox("");
				deadlineCheckbox.addActionListener(new ActionListener()
				{
					@Override
					public void actionPerformed(ActionEvent arg0) {
						if(deadlineCheckbox.isSelected())
						{
							dayTextField.setEditable(true);
							monthTextField.setEditable(true);
							yearTextField.setEditable(true);
						}
						else
						{
							dayTextField.setEditable(false);
							monthTextField.setEditable(false);
							yearTextField.setEditable(false);							
						}
					}					
				});
				panel.add(deadlineCheckbox);
			}
			{
				JLabel lblDay = new JLabel("Day");
				panel.add(lblDay);
			}
			{
				dayTextField = new JTextField();
				dayTextField.setEditable(false);
				dayTextField.setColumns(2);
				dayTextField.setText(today.getDayOfMonth() + "");
				panel.add(dayTextField);
			}
			{
				JLabel lblMonth = new JLabel("Month");
				panel.add(lblMonth);
			}
			{
				monthTextField = new JTextField();
				monthTextField.setEditable(false);
				monthTextField.setColumns(2);
				monthTextField.setText(today.getMonthOfYear() + "");
				panel.add(monthTextField);
			}
			{
				JLabel lblYear = new JLabel("Year");
				panel.add(lblYear);
			}
			{
				yearTextField = new JTextField();
				yearTextField.setEditable(false);
				yearTextField.setColumns(4);
				yearTextField.setText(today.getYear() + "");
				panel.add(yearTextField);
			}
		}
		{
			JLabel lblDescription = new JLabel("Description");
			GridBagConstraints gbc_lblDescription = new GridBagConstraints();
			gbc_lblDescription.insets = new Insets(0, 0, 0, 5);
			gbc_lblDescription.gridx = 0;
			gbc_lblDescription.gridy = 5;
			contentPanel.add(lblDescription, gbc_lblDescription);
		}
		{
			descriptionTextPane = new JTextPane();
			GridBagConstraints gbc_descriptionTextPane = new GridBagConstraints();
			gbc_descriptionTextPane.fill = GridBagConstraints.BOTH;
			gbc_descriptionTextPane.gridx = 1;
			gbc_descriptionTextPane.gridy = 5;
			contentPanel.add(descriptionTextPane, gbc_descriptionTextPane);
		}
		{
			JPanel buttonPane = new JPanel();
			buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT));
			final CreateEditTaskDialog thisDialog = this;
			getContentPane().add(buttonPane, BorderLayout.SOUTH);
			{
				JButton okButton = new JButton("OK");
				okButton.addActionListener(new ActionListener()
					{
						@Override
						public void actionPerformed(ActionEvent arg0) {
							if(validateInput())
							{
								status = Status.OK;
								thisDialog.dispose();
							}
						}	
					}
				);
				okButton.setActionCommand("OK");
				buttonPane.add(okButton);
				getRootPane().setDefaultButton(okButton);
			}
			{
				JButton cancelButton = new JButton("Cancel");
				cancelButton.setActionCommand("Cancel");
				cancelButton.addActionListener(new ActionListener()
				{
					@Override
					public void actionPerformed(ActionEvent arg0) {
						status = Status.CANCEL;
						thisDialog.dispose();
					}	
				}
				);
				buttonPane.add(cancelButton);
			}
		}
	}
	
	public String getName()
	{
		return nameField.getText();
	}
		
	public LocalDate getDeadlineDate()
	{
		Integer day = Integer.valueOf(dayTextField.getText());
		Integer month = Integer.valueOf(monthTextField.getText());
		Integer year = Integer.valueOf(yearTextField.getText());
		LocalDate date = new LocalDate(year, month, day);
		return date;
	}

	public boolean hasDeadline()
	{
		return deadlineCheckbox.isSelected();
	}
	
	public MinTime getTime()
	{
		Integer minutes = Integer.valueOf(minutesTimeField.getText());
		Integer hours = Integer.valueOf(hoursTimeField.getText());
		return new MinTime(hours, minutes);
	}
	
	public TaskType getTaskType()
	{
		return (TaskType)typeComboBox.getSelectedItem();
	}
	
	public String getDescription()
	{
		return descriptionTextPane.getText();
	}

	public String getCategoryName()
	{
		return (String)categoryComboBox.getSelectedItem();
	}
	
	public Status getStatus()
	{
		return status;
	}
	
	public boolean validateInput()
	{
		if(getName().trim().equals(""))
		{
			JOptionPane.showMessageDialog(this,
				    "Task must have name",
				    "Name error",
				    JOptionPane.ERROR_MESSAGE);		
			return false;			
		}
		try
		{
			getDeadlineDate();
			getTime();
			return true;
		}
		catch(RuntimeException e)
		{
			JOptionPane.showMessageDialog(this,
				    e.getMessage(),
				    "Creation error",
				    JOptionPane.ERROR_MESSAGE);		
			return false;
		}

	}
}
